package com.liu.activiti.handler;

import com.liu.activiti.enums.HttpStateEnum;
import com.liu.activiti.exception.CustomException;
import com.liu.activiti.pojo.UserDetail;
import com.liu.activiti.utils.JwtUtil;
import com.liu.activiti.utils.ResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用户登录成功触发
 */
@Component
@Slf4j
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        UserDetail userDetail = (UserDetail)authentication.getPrincipal();
        // 用户认证成功后生成 JWT token
        String token = JwtUtil.generateToken(userDetail.getUser());
        response.addHeader(HttpHeaders.AUTHORIZATION, "Bearer " + token);
//        response.flushBuffer();
        ResponseUtils.endResponse(response,new CustomException("登陆成功！token在Header中", HttpStateEnum.SUCCEED.getCode()));

        log.info("用户登录成功 ... 开始正常工作 token = {}", "Bearer " + token);
    }
}
